<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>cart</title>
</head>
<body>
<div id="app" style="width:30%;margin:auto;">
    <table>
        <thead>
            <tr>
                <th>名称</th>
                <th>数量</th>
                <th>单价</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(product,index) in products">
                <td>{{product.name}}</td>
                <td>
                    <button @click="increaseQuantity(index)">+</button>
                    <input v-model="product.quantity" style="width:80px"/>
                    <button @click="decreaseQuantity(index)">-</button>
                </td>
                <td>{{product.price}}</td>
                <td>{{product.price*product.quantity}}</td>
                <td><button @click="removeProduct(index)">删除</button></td>
            </tr>
        </tbody>
    </table>
    <div>
        <p>总数量:{{totalQuantity}}</p>
        <p>总金额:{{totalPrice|currency}}</p>
        <p>最高单价商品:{{maxPrice|currency}}</p>
    </div>
</div>
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script>
  var vm = new Vue({
    el:'#app',
    data:{
        products: [
          { name: 'iphone5', price: 500, quantity: 1 },
          { name: 'iphone6', price: 600, quantity: 1 },
          { name: 'iphone7', price: 700, quantity: 1 },
        ]
    },
    methods:{
        increaseQuantity(index){//增加索引对应的商品的数量
            this.products[index].quantity++;
        },
        decreaseQuantity(index){//减少索引对应商品的数量
            //如果现在商品的数量大于1，就减少1个
            if(this.products[index].quantity>1){
                this.products[index].quantity--;
            }else{//否则就把当前的商品删除
                this.removeProduct(index);
            }
        },
        removeProduct(index){
            //从索引入删除一个商品
            this.products.splice(index,1);
        }
    },
    filters:{
        currency(value){
            return '$'+value;
        }
    },
    computed:{
        totalQuantity(){
            return this.products.reduce((result,product)=>{
                return result+product.quantity;
            },0);
        },
        totalPrice(){
            return this.products.reduce((result,product)=>{
                //每项商品的价格乘以数量得到了小计，把每个商品的小计加在一起就是最后的总价
                return result+product.quantity*product.price;
            },0);
        },
        maxPrice(){
            //循环迭代每一个商品,判断
            return this.products.reduce((result,product)=>{
                //如果当前商品价格高于result,那就返回当前的商品的价格
                if(product.price>result){
                    return product.price
                }else{//还使用老价格
                    return result;
                }
            },0);
        }
    }
  });
</script>
</body>
</html>